import React, { useEffect, useRef, useState } from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { Button, Result, Space, Tag, TreeSelect } from 'antd';
import { ActionType, LightFilter, ProFormDateRangePicker, ProFormSelect, ProFormTreeSelect, ProList, ProTable } from '@ant-design/pro-components';
import TableTableTopicRenderDetails from './TableTopicRenderDetails';
import { pageCuesTopic, pageCuesTopicInit } from '@/services/api/api-cues-topic';
import { parse } from '@/utils/historyUtils';
import { useAccess } from '@umijs/max';
import ReceiptReport from '../components/ReceiptReport';
interface TableIntelligentRecommendationProps {
    mode: number;
    loading: boolean;
    onRefurbish: () => void;
}
const TableIntelligentRecommendation: React.FC<TableIntelligentRecommendationProps> = ({ mode, loading, onRefurbish }) => {
    const userRef = useRef<ActionType>();
    const userRefList = useRef<ActionType>();
    const [topicId, setTopicIdState] = useState()
    const access = useAccess();
    /**
      * 请求网络
      * @param value
      */
    const request = async (params = {}) => {
        const response = await pageCuesTopic({ pageSize: 12, current: 1, mode: mode, run: 1, createdSource: 3 });
        return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
        });
    };

    /**
 * 请求网络
 * @param value
 */
    const requestTable = async (params = {}, filter = {}) => {
        console.log(filter);
        const response = await pageCuesTopic({ ...params, mode: mode, ...queryParam, run: 2, createdSource: 3 });
        return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
        });
    };
    /**
    * 搜索参数
    */
    const [queryParam, setQueryParamState] = useState({});

    useEffect(() => {
        const { topicId } = parse(location.search) as { topicId: string };
        setTopicIdState(topicId);
    }, [])

    /**
  * 预备Tree结构数据
  * @param data
  */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    key: val.id,
                    disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined, children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }
    /**
 * 查询单位
 */
    const [queryOrganizations, setQueryOrganizationsState] = useState<any>();

    /**
     * 加载 页面初始化信息
     * @param key
     */
    const loadPageCuesTopicInitData = async () => {
        try {
            const response = await pageCuesTopicInit({ mode: mode });
            if (response.code === 0) {
                setQueryOrganizationsState(readyTreeData(response.data.queryOrganizations));
            }
        } catch (error) { }
    };
    useEffect(() => {
        loadPageCuesTopicInitData();
    }, []);
    return (
        <>
            <ProList<CuesTopicData.TopicPage>
                header={false}
                headerTitle={false}
                actionRef={userRefList}
                request={request}
                showActions="hover"
                grid={{ gutter: 18, column: 4 }}
                onItem={(record: any) => {
                    return {
                        onMouseEnter: () => { },
                        onClick: () => { },
                    };
                }}
                renderItem={(item: CuesTopicData.TopicPage, index: number) => {
                    return (
                        <TableTableTopicRenderDetails
                            type="intelligent"
                            topicId={topicId}
                            item={item}
                            onRefurbish={() => {
                                userRef.current?.reload();
                                userRefList.current?.reload();
                            }}
                            triggerMode="card"
                            title={item.name}
                        />
                    );
                }}
                rowKey={'id'}
                toolBarRender={false}
            />
            <ProTable<CuesTopicData.TopicPage>
                columns={[
                    {
                        title: '选题标题',
                        key: 'name',
                        dataIndex: 'name',
                        width: '180px',
                        search: false,
                        ellipsis: true,
                        render: (_, row) => (
                            <>
                                {row.isLinkage === 1 && (
                                    <Tag color="orange">
                                        {row.linkageType === 1
                                            ? '协助媒体'
                                            : row.linkageType === 2
                                                ? '联动部门'
                                                : row.linkageType === 3
                                                    ? '协助媒体、单位'
                                                    : '暂无'}
                                    </Tag>
                                )}
                                <Tag color={row.grade === 1 ? '#f50' : row.grade === 2 ? '#ffd591' : '#2db7f5'}>
                                    {row.grade === 1 ? '重大' : row.grade === 2 ? '重要' : '一般'}
                                </Tag>
                                <Tag color={row.run === 1 ? 'green' : row.run === 2 ? 'red' : 'orange'}>
                                    {row.run === 1 ? '进行中' : row.run === 2 ? '已结束' : '已暂停'}
                                </Tag>
                                {row.showView === 1 && row.isView === 0 ? (
                                    <Tag color="red">未阅读</Tag>
                                ) : row.showSubmit === 1 && row.isSubmit === 0 ? (
                                    <Tag color="red">未报送</Tag>
                                ) : (
                                    <></>
                                )}
                                <TableTableTopicRenderDetails
                                    topicId={topicId}
                                    item={row}
                                    onRefurbish={() => {
                                        userRef.current?.reload();
                                        userRefList.current?.reload();
                                    }}
                                    triggerMode="title"
                                    title={row.name}
                                />
                            </>
                        ),
                    },
                    {
                        title: '报送单位',
                        dataIndex: 'createdOrganizationAvatar',
                        key: 'createdOrganizationAvatar',
                        width: '100px',
                        valueType: 'avatar',
                        render: (dom, row) => (
                            <Space>
                                <span>{dom}</span>
                                {row.createdOrganizationName}
                            </Space>
                        ),
                    },
                    {
                        title: '截止时间',
                        dataIndex: 'deadlineTime',
                        key: 'deadlineTime',
                        width: '80px',
                        align: 'center',
                        valueType: 'dateTime',
                    },
                    {
                        title: '报送线索',
                        dataIndex: 'countSubmit',
                        key: 'countSubmit',
                        width: '50px',
                        align: 'center',
                        search: false,
                    },
                    {
                        title: '报送单位',
                        dataIndex: 'countSubmitOrganization',
                        key: 'countSubmitOrganization',
                        width: '50px',
                        align: 'center',
                        hideInTable: access.线索征集x配置x提供者,
                        search: false,
                    },
                    {
                        title: '阅读情况',
                        hideInSearch: true,
                        hideInTable: access.线索征集x配置x提供者,
                        dataIndex: 'receipt',
                        key: 'receipt',
                        valueType: 'avatar',
                        width: '80px',
                        align: 'center',
                        search: false,
                        render: (dom, record) => (<>
                            <ReceiptReport id={record.id} receipt={record.receipt} onRefurbish={() => {
                                userRef.current?.reload();
                                userRefList.current?.reload();
                            }} />
                        </>),
                    },
                ]}
                headerTitle={false}
                ghost={true}
                pagination={{
                    defaultPageSize: 9,
                    showSizeChanger: false,
                }}
                search={false}
                actionRef={userRef}
                request={requestTable}
                rowKey={'id'}
                toolbar={{
                    search: {
                        onChange: (e) => {
                            setQueryParamState({ ...queryParam, name: e.target.value });
                        },
                        onSearch: (value) => {
                            userRef.current?.reset();
                        },
                    },
                    filter: (
                        <LightFilter
                            // initialValues={{ run: 2 }}
                            onValuesChange={(value) => {
                                setQueryParamState(value);
                                userRef.current?.reset();
                            }}
                        >
                            <ProFormSelect
                                name="grades"
                                label="分类"
                                mode="multiple"
                                options={[
                                    {
                                        label: '重大',
                                        value: 1,
                                    },
                                    {
                                        label: '重要',
                                        value: 2,
                                    },
                                    {
                                        label: '一般',
                                        value: 3,
                                    },
                                ]}
                            />
                            <ProFormSelect
                                hidden={!access.线索征集x配置x提供者}
                                name="isView"
                                label="阅读"
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    },
                                ]}
                            />
                            <ProFormSelect
                                hidden={!access.线索征集x配置x提供者}
                                name="isSubmit"
                                label="报送"
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    },
                                ]}
                            />
                            <ProFormDateRangePicker name="deadlineTimes" label="截止范围" allowClear />

                            <ProFormTreeSelect
                                name="createdOrganizationIds"
                                label="发布单位"
                                width="xl"
                                placeholder="选择单位"
                                fieldProps={{
                                    treeData: queryOrganizations,
                                    treeCheckable: true,
                                    showCheckedStrategy: TreeSelect.SHOW_PARENT,
                                }}
                            />
                        </LightFilter>
                    ),
                }}
            />
        </>
    )
};

export default TableIntelligentRecommendation;